/**
 * 
 */
package com.itinsys.enma.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import org.hibernate.type.Type;
/**
 * @author pferraz
 * 
 */
public class Utils {

	
	public static String readContentFromFile(String filePath) throws IOException {
		FileInputStream fIS = new FileInputStream(new File(filePath));
		String result=null;
		try {
			FileChannel fC = fIS.getChannel();
			MappedByteBuffer mBB = fC.map(FileChannel.MapMode.READ_ONLY, 0,fC.size());
			result=Charset.defaultCharset().decode(mBB).toString();
		} finally {
			fIS.close();
		}
		
		return result;
	}
	
	public static Date stringPeriodDateToDate(String periodDate){
		SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
			
		try {
			return new Date(dateFormatter.parse(periodDate).getTime());
		} catch (ParseException e) {
			return new Date(0);
		}
	}
	
	public static int compare(Calendar c1, Calendar c2) {
	    if (c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)) 
	        return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
	    if (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH)) 
	        return c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
	    return c1.get(Calendar.DAY_OF_MONTH) - c2.get(Calendar.DAY_OF_MONTH);
	 }
	
	/**
	 * @param conds
	 * @param objects
	 * @param types
	 * @return
	 */
	public static HQLConditionResult getArrayHQLFromLists(List<String> conds,List<Object> objects, List<Type> types) {
		Object[] objs=new Object[objects.size()];
		Type[] typs=new Type[types.size()];
		
		String strCond="";
		for(int i=0;i<objs.length;i++){
			if(i>0&&i<conds.size())
				strCond+=" and ";
			if(i<conds.size())
				strCond+=conds.get(i);
			objs[i]=objects.get(i);
			typs[i]=types.get(i);
				
		}
		return new HQLConditionResult(objs, typs, strCond);
	}
	
	public static Date getMondayOfTheActualWeek(){
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		
		return new Date(c.getTime().getTime());
	}

}
